<template>
    <div class="app-container">
        <div class="customContainer">
            <!-- 头 -->
            <div class="customHeader">
                <div class="pull-left">
                    {{machineInfo.store_name}}&#x3000;{{machineInfo.area_name}}&#x3000;{{machineInfo.machine_type}}&#x3000;机台编号：{{machineInfo.no}}&#x3000;机台ID：{{machineInfo.machine_id}}
                </div>
                <span class="pull-right">
                    <el-button type="primary" size="small" @click="goBatch()">批量新增卡头</el-button>
                    <el-button type="primary" size="small" @click="addEditClick()">新增卡头</el-button>
                </span>
            </div>
            <!-- 列表 -->
            <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
                <el-table-column align="center" label='序号' width="50" :key="$route.params.machine_id">
                    <template slot-scope="scope">
                        <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="卡头ID" prop="id" width="80"></el-table-column>
                <el-table-column align="center" label='卡头编号' prop="clevice_no"></el-table-column>
                <el-table-column align="center" label='卡头类型' prop="type">
                    <template slot-scope="scope">
                        {{scope.row.type==0 ?'常规卡头':scope.row.type==1 ?'湖心岛门票区门票':scope.row.type==2
                        ?'湖心岛门票区陪同票':scope.row.type==3 ?'湖心岛门票区销售':'-' }}
                    </template>
                </el-table-column>
                <el-table-column align="center" label="会员价" prop="coins_sell_vip"></el-table-column>
                <el-table-column align="center" label='非会员价' prop="coins_sell"></el-table-column>
                <el-table-column align="center" label='星星数' prop="stars"></el-table-column>
                <el-table-column align="center" label="脉冲数" prop="pulse"></el-table-column>
                <el-table-column align="center" label="次数" prop="times"></el-table-column>
                <el-table-column align="center" label='所属机台ID' prop="machine_id"></el-table-column>
                <el-table-column align="center" label='所属机台类型' prop="machine_type"></el-table-column>
                <el-table-column align="center" label='支持关联礼品'>
                    <template slot-scope="scope">
                        {{scope.row.is_gift_mapping ==1? '支持' : '不支持'}}
                    </template>
                </el-table-column>
                <el-table-column align="center" label='关联礼品' prop="gift_name"></el-table-column>
                <el-table-column align="center" label='备注' width="100" prop="remark"></el-table-column>
                <el-table-column align="center" label="扫码支付套餐">
                    <template slot-scope="scope">
                        <el-button @click="scanSetClick(scope.row,'edit')" type="primary" size="mini">设置</el-button>
                    </template>
                </el-table-column>
                <!-- 列表的操作按钮 -->
                <el-table-column align="center" label="操作" width="140">
                    <template slot-scope="scope">
                        <el-button @click="addEditClick(scope.row.id,scope.$index)" type="primary" icon="el-icon-edit"
                            size="mini"></el-button>
                        <el-button @click="delClick(scope.row.id,scope.$index)" type="danger" icon="el-icon-delete"
                            size="mini"></el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 弹框 -->
            <el-dialog width="660px" :close-on-click-modal="false" :title="dialogTitle" :visible.sync="addCleviceDialog"
                @close="callOf('saveForm')">
                <div style="position:relative;bottom:20px;">
                    {{machineInfo.store_name}}&#x3000;{{machineInfo.area_name}}&#x3000;{{machineInfo.machine_type}}&#x3000;机台编号：{{machineInfo.no}}&#x3000;机台ID：{{machineInfo.machine_id}}
                </div>
                <el-form :model="saveForm" :inline="true" ref="saveForm" :rules="rules"
                    style="width:620px;margin:0 auto;">
                    <div class="customHeader" v-if="isAdd">
                        <el-input v-model="clevice_id" class="w200" placeholder="请输入卡头ID"></el-input>
                        <el-button type="primary" :disabled="!clevice_id" @click="searchCleviceClick">搜 索</el-button>
                        <div class="pull-right">
                            <el-button type="primary" @click="addCleviceClick">新建卡头</el-button>
                        </div>
                    </div>
                    <br>
                    <el-form-item label="　会员价" prop="coins_sell_vip">
                        <el-input v-model="saveForm.coins_sell_vip" class="w200" :disabled="isDisabled"></el-input>
                    </el-form-item>
                    <el-form-item class="pull-right" label="非会员价" prop="coins_sell">
                        <el-input v-model="saveForm.coins_sell" class="w200" :disabled="isDisabled"></el-input>
                    </el-form-item>
                    <el-form-item label="　脉冲数" prop="pulse">
                        <el-input v-model="saveForm.pulse" class="w200" :disabled="isDisabled"></el-input>
                    </el-form-item>
                    <el-form-item class="pull-right" prop="stars" label="星星数">
                        <el-input v-model="saveForm.stars" class="w200" :disabled="isDisabled"></el-input>
                    </el-form-item>
                    <el-form-item label="卡头类型" prop="type">
                        <el-select placeholder="卡头类型" v-model="saveForm.type" filterable>
                            <el-option v-for="item in clevice_type" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class="pull-right" label="· 　备　注">
                        <el-input :maxlength="50" v-model="saveForm.remark" class="w200"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-checkbox class="w200" v-model="isGiftMapping" label="支持关联礼品" border></el-checkbox>
                        &nbsp;
                    </el-form-item>
                    <el-form-item class="pull-right" prop="times" label="次数">
                        <el-input v-model="saveForm.times" class="w200" :disabled="isDisabled"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" v-if="dialogTitle=='添加卡头'" @click="saveClick('saveForm','keep')">添加并设置套餐
                    </el-button>
                    <el-button type="primary" @click="saveClick('saveForm')">{{dialogTitle=='添加卡头' ?'添加':'保存'}}
                    </el-button>
                    <el-button @click="callOf('saveForm')">取 消</el-button>
                    &nbsp;
                </div>
            </el-dialog>
            <el-dialog width="660px" :close-on-click-modal="false" :title="scanTitle" :visible.sync="scanSetDialog">
                <div v-if="scanTitle=='修改扫码套餐'" style="position:relative;top:-20px;">卡头ID：{{package_info.id}}
                    &#x3000;&#x3000;卡头编号：{{package_info.clevice_no}} &#x3000;&#x3000;所属品牌：{{package_info.brand_name}}
                </div>
                <div v-show="scanTitle=='修改扫码套餐'">
                    <el-checkbox v-model="is_sweep" @change="sweepChange">支持扫码支付</el-checkbox>
                    <br> <br>
                </div>
                <el-checkbox :disabled="!is_sweep" v-model="is_mida" @change="midaChange">咪哒KTV</el-checkbox>&#x3000;
                <el-select :disabled="is_mida||!is_sweep" placeholder="套餐" size="mini" v-model="scanForm.combo_id"
                    filterable @change="mealChange">
                    <el-option v-for="item in package_list" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
                <br> <br>
                <el-table highlight-current-row :data="scanForm.rules" v-loading.body="listLoading" border size="mini">
                    <el-table-column align="center" label='按钮' width="80">
                        <template slot-scope="scope">
                            <span class="indexColor">按钮{{scope.$index+1}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label='扫码金额（元）' prop="money"></el-table-column>
                    <el-table-column v-if="!is_mida" align="center" label='游玩次数（次）' prop="times"></el-table-column>
                    <el-table-column v-if="is_mida" align="center" label='游玩时间（分钟）' prop="times"></el-table-column>
                    <el-table-column align="center" label='首单赠送' width="80" v-if="!is_mida">
                        <template slot-scope="scope">
                            <el-checkbox disabled v-model="scope.row.is_give"></el-checkbox>
                        </template>
                    </el-table-column>
                </el-table>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="scanSaveClick('saveForm')">{{scanTitle=='扫码设置' ?'确认':'保存'}}
                    </el-button>
                    <el-button v-if="scanTitle=='扫码设置'" @click="scanSetDialog=false">跳过</el-button>
                    &nbsp;
                </div>
            </el-dialog>
        </div>

        <!-- 自定义底部 -->
        <div class="bottom_box">
            <el-pagination class="pull-left" background @current-change="handleCurrentChange"
                :current-page.sync="currentPage" :page-size="20" layout="prev, pager, next, jumper"
                :total="totalDataNumber">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import {
        getList,
        getPage,
        del,
        getEditMachine,
        getClevice,
        saveClevice,
        get_package,
        scanSave
    } from "@/api/information/deployclevice";
    import { num1to255, nullOr1to255, integer1to999999999} from '@/utils/validate'
    export default {
        data() {
            const validateVal = (rule, value, callback) => {
                if (!num1to255(value)) {
                    callback(new Error('请输入1-255数字'))
                } else {
                    callback()
                }
            }
            const validateVal2 = (rule, value, callback) => {
                if (!nullOr1to255(value)) {
                    callback(new Error('可不填，要填就填1-255数字'))
                } else {
                    callback()
                }
            }
            const validateVal3 = (rule, value, callback) => {
                if(!value=='' && !integer1to999999999(value)){
                    callback(new Error("可不填，要填就填大于0的数字"));
                }else {
                    callback();
                }
            };
            return {
                scanTitle: '',
                package_info: { id: '' },
                package_list: [],
                mida_list: [{ money: "15", times_first: "3", times: "3" }, { money: "25", times_first: "5", times: "5" }, { money: "40", times_first: "8", times: "8" }, { money: "50", times_first: "10", times: "10" }, { money: "75", times_first: "15", times: "15" }],
                is_sweep: true,
                is_mida: false,
                scanSetDialog: false,
                clevice_type: [{ id: '0', name: '常规卡头' }, { id: '1', name: '湖心岛门票区门票' }, { id: '2', name: '湖心岛门票区陪同票' }, { id: '3', name: '湖心岛门票区销售' }],
                machineInfo: {},
                isGiftMapping: false,
                isDisabled: false,
                isAdd: true,
                dialogTitle: '',
                editIndex: '',
                searchCleviceInfo: '',
                clevice_id: '',
                url: '',
                list: null,
                listLoading: false,
                currentPage: 1,
                totalDataNumber: 0,
                formInline: { machine_id: '' },
                saveForm: {
                    machine_id: this.$route.params.machine_id,
                    coins_sell_vip: "",
                    coins_sell: "",
                    pulse: "",
                    remark: "",
                    is_gift_mapping: "",
                    type: '',
                    stars: '',
                    times: ''
                },
                scanForm: {
                    id: '',
                    combo_id: '',
                    rules: [{ money: '', times: '', times_first: '', is_give: false }],
                },
                newForm: {},
                rules: {
                    coins_sell_vip: [
                        { required: true, trigger: 'blur', validator: validateVal },
                    ],
                    coins_sell: [
                        { required: true, trigger: 'blur', validator: validateVal },
                    ],
                    pulse: [
                        { required: true, trigger: 'blur', validator: validateVal },
                    ],
                    stars: [
                        { required: false, trigger: 'blur', validator: validateVal2 },
                    ],
                    type: [
                        { required: true, message: '选择卡头类型', trigger: 'change' }
                    ],
                    times: [
                        { required: false, trigger: 'blur', validator: validateVal3 },
                    ]
                },
                addCleviceDialog: false,
            };
        },
        beforeRouteEnter(to, from, next) {
            next((vm) => {//当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
                vm.beforeComingIn();
            })
        },
        methods: {
            beforeComingIn() {
                if (this.$route.params.routerflag || this.formInline.machine_id != this.$route.params.machine_id) {
                    this.formInline.machine_id = this.$route.params.machine_id;
                    this.fetchData();
                }
            },
            goBatch() {
                this.$router.push({
                    name: 'information/clevice_batch_add',
                    params: {
                        brand_id: this.$route.params.brand_id,
                        store_id: this.$route.params.store_id,
                        machine_id: this.$route.params.machine_id,
                        routerflag: 1
                    },
                })
            },
            scanSaveClick() {
                let data = {};
                data.id = this.scanForm.id;
                data.combo_id = this.scanForm.combo_id;
                data.is_sweep = this.is_sweep ? 1 : 0;
                if (this.is_mida) {
                    data.combo_id = '6'
                }
                if (this.is_sweep && !this.is_mida && this.scanForm.combo_id == '') {
                    this.$message({ type: 'error', message: '请选择套餐' });
                    return;
                }
                scanSave(data).then(response => {
                    this.$message({ type: 'success', message: response.message });
                    if (response.code == 1) {
                        this.handleCurrentChange(this.currentPage)
                        this.scanSetDialog = false;
                    }
                });
            },
            sweepChange() {
                if (!this.is_sweep) {
                    this.is_mida = false;
                    this.scanForm.rules = [];
                    return;
                }
            },
            midaChange() {
                this.scanForm.rules = [];
                if (this.is_mida) {
                    this.scanForm.combo_id = '';
                    this.scanForm.rules = this.mida_list;
                    console.log(this.mida_list)
                    return;
                }
                this.mealChange();
            },
            mealChange() {
                let item_list = this.scanForm.combo_id == '' ? [] : (this.package_list.filter((item, i) => { return item.id == this.scanForm.combo_id }))[0].rules;
                item_list.forEach(val => {
                    val.is_give = (val.times_first * 1 > val.times * 1) ? true : false;
                });
                this.scanForm.rules = item_list
                if (this.is_mida && this.scanForm.combo_id == '') {
                    this.scanForm.rules = this.mida_list;
                }
            },
            scanSetClick(row, edit) {
                this.scanTitle = edit == 'edit' ? '修改扫码套餐' : '扫码设置';
                this.scanForm.id = row.id
                this.package_list = [];
                this.package_info = row;
                this.is_sweep = row.is_sweep == 1 ? true : false;
                this.is_mida = row.combo_id == 6 ? true : false;
                this.scanForm.combo_id = row.combo_id == 6 ? '' : row.combo_id;
                get_package({ all: 1, brand_id: row.brand_id }).then(response => {
                    this.package_list = response.filter((item, i) => { return item.id != 6 })
                    this.mealChange();
                });
                this.scanSetDialog = true
            },
            // 提交
            saveClick(formName, keep) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.newForm = this.saveForm
                        this.newForm.is_gift_mapping = this.isGiftMapping == true ? 1 : 0;
                        if (this.clevice_id) {
                            this.newForm.clevice_id = this.clevice_id
                        }
                        saveClevice(this.newForm, this.url).then(response => {
                            if (response.code == 1) {
                                this.$message({ type: 'success', message: response.message, });
                                this.handleCurrentChange(this.currentPage)
                                this.addCleviceDialog = false;
                                if (keep) {
                                    this.scanSetClick({ id: response.id ? response.id : this.scanForm.id, is_sweep: 1, combo_id: '', brand_id: this.machineInfo.brand_id });
                                }
                            }
                        });
                    }
                });
            },
            // 编辑和新增弹框
            addEditClick(id, index) {
                this.dialogTitle = id ? '编辑卡头' : '添加卡头';
                this.editIndex = ''
                this.isAdd = true;
                this.addCleviceDialog = true;
                this.url = "/Machine_clevice/create_machine_clevice";//新建URL
                if (id) {
                    this.url = '/Machine_clevice/update_machine_clevice';//编辑提交URL
                    this.editIndex = index;
                    this.isAdd = false;
                    this.clevice_id = id;
                    this.saveForm.coins_sell_vip = this.list[index].coins_sell_vip
                    this.saveForm.coins_sell = this.list[index].coins_sell
                    this.saveForm.pulse = this.list[index].pulse
                    this.saveForm.type = this.list[index].type
                    this.saveForm.remark = this.list[index].remark
                    this.saveForm.stars = this.list[index].stars == 0 ? '' : this.list[index].stars;
                    this.isGiftMapping = this.list[index].is_gift_mapping == 1 ? true : false;
                    this.saveForm.times = this.list[index].times == 0 ? '' : this.list[index].times;
                } else {
                    this.saveForm = {
                        machine_id: this.$route.params.machine_id,
                        type: '',
                        coins_sell_vip: "",
                        coins_sell: "",
                        pulse: "",
                        remark: "",
                        stars: "",
                        is_gift_mapping: "",
                    }
                }
            },

            // 新建卡头
            addCleviceClick() {
                this.$refs['saveForm'].resetFields();
                this.url = "/Machine_clevice/create_machine_clevice";//新建URL
                this.saveForm.coins_sell = ''
                this.saveForm.coins_sell_vip = ''
                this.saveForm.is_gift_mapping = ''
                this.saveForm.stars = ''
                this.saveForm.times = ''
                this.saveForm.pulse = ''
                this.isDisabled = false;
                this.clevice_id = '';
                this.saveForm.remark = "";
                this.isGiftMapping = false;
            },
            // 卡头搜索
            searchCleviceClick() {
                getClevice({ clevice_id: this.clevice_id }).then(response => {
                    this.$refs['saveForm'].resetFields();
                    if (response.list.length > 0) {
                        this.scanForm.id = this.clevice_id;
                        this.url = '/Machine_clevice/machine_clevice_mapping';//添加搜索出来的URL
                        this.searchCleviceInfo = response.list[0]
                        this.saveForm.coins_sell_vip = this.searchCleviceInfo.coins_sell_vip
                        this.saveForm.coins_sell = this.searchCleviceInfo.coins_sell
                        this.saveForm.pulse = this.searchCleviceInfo.pulse
                        this.saveForm.remark = this.searchCleviceInfo.remark
                        this.saveForm.clevice_no = this.searchCleviceInfo.clevice_no ? this.searchCleviceInfo.clevice_no : '-';  //后端不在 卡头编号不需要，临时改传-，传0或不传都不行，我擦？
                        this.saveForm.type = this.searchCleviceInfo.type
                        this.saveForm.stars = this.searchCleviceInfo.stars == 0 ? '' : this.searchCleviceInfo.stars
                        this.isGiftMapping = this.searchCleviceInfo.is_gift_mapping == 1 ? true : false
                         this.saveForm.times = this.searchCleviceInfo.times == 0 ? '' : this.searchCleviceInfo.times
                        this.isDisabled = true
                    } else {
                        this.$refs['saveForm'].resetFields();
                        this.isDisabled = false;
                        this.clevice_id = '';
                        this.saveForm = {
                            machine_id: this.$route.params.machine_id,
                            coins_sell_vip: "",
                            coins_sell: "",
                            type: "",
                            pulse: "",
                            remark: "",
                            is_gift_mapping: "",
                        }
                        this.isGiftMapping = false;
                        this.$message({
                            type: 'error',
                            message: '找不到该卡头，请重新输入'
                        });
                    }
                });
            },
            // 删除按钮
            delClick(id, index) {
                this.$confirm('此操作删除, 是否继续?', '提示', { type: 'warning' }).then(() => {
                    del({ clevice_id: id, machine_id: this.$route.params.machine_id }).then(response => {
                        if (response.code == 1) {
                            this.list.splice(index, 1);
                            this.$message({ type: 'success', message: '删除成功' });
                        } else {
                            this.$message({ type: 'error', message: response.message });
                        }
                    });
                })
            },
            // 列表获取
            fetchData() {
                this.listLoading = true;
                this.currentPage = 1;
                getPage(this.formInline).then(response => {
                    this.totalDataNumber = response.count * 1;
                    getList(this.formInline).then(response => {
                        this.machineInfo = response.machine;
                        this.list = response.list;
                        this.listLoading = false;
                    }).catch(err => {
                        this.listLoading = false;
                    })
                }).catch(err => {
                    this.listLoading = false;
                })
            },
            // 分页
            handleCurrentChange(val) {
                this.listLoading = true;
                getList(this.formInline, val).then(response => {
                    this.list = response.list;
                    this.listLoading = false;
                });
            },
            //关闭弹框重置
            callOf(formName) {
                this.$refs[formName].resetFields();
                this.addCleviceDialog = false;
                this.isDisabled = false;
                this.clevice_id = '';
                this.saveForm.remark = "";
                this.isGiftMapping = false;
            },
        }
    };
</script>